package sns.service;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.springframework.transaction.annotation.Transactional;
import sns.bean.User;
import sns.dao.RelationDao;
import sns.dao.UserDao;

@Transactional
public class UserService {

	private UserDao userDao;
	private RelationDao relationDao;

	/**
	 * Get the user who has logged in
	 * 
	 * @return
	 */
	@Transactional
	public User getCurrentUser(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String username = (String) request.getSession().getAttribute("SPRING_SECURITY_LAST_USERNAME");
		if (username == null){
			return null;
		}
		User user = userDao.findByUsername(username);
		return user;
	}
	
	/**
	 * user log out
	 */
	@Transactional
	public void userLogout(){
		HttpServletRequest request = ServletActionContext.getRequest();
		request.getSession().removeAttribute("SPRING_SECURITY_LAST_USERNAME");
	}
	
	/**
	 * Get the top n users ordered by number of followers
	 * @param n
	 * @return
	 */
	public List<User> getHotUsers(int n){
		return relationDao.getHotUsers(0,n);
	}
	
	/**
	 * get user by its id
	 * 
	 * @param iduser
	 * @return
	 */
	public User findUserById(Long iduser){
		return userDao.findUserById(iduser);
	}
	
	/**
	 * find the user by username
	 * 
	 * @param username
	 * @return
	 */
	public User findByUsername(String username){
		return userDao.findByUsername(username);
	}
	
	/**
	 * get the recently n registered users
	 * 
	 * @param n
	 * @return
	 */
	public List<User> getNewUsers(int n){
		return userDao.getNewUsers(n);
	}
	
	/**
	 * get the followers, i.e. fans
	 * 
	 * @param user
	 * @return
	 */
	public List<User> getFollowers(User user){
		return relationDao.getFollowers(user);
	}
	
	/**
	 * get the first n followers of the user
	 * 
	 * @param user
	 * @param n
	 * @return
	 */
	public List<User> getNFollowers(User user, int n){
		return relationDao.getMinMaxFollowers(user, 0, n);
	}
	
	/**
	 * get the followees, i.e. idols
	 * 
	 * @param user
	 * @return
	 */
	public List<User> getFollowees(User user){
		return relationDao.getFollowees(user);
	}
	
	/**
	 * get the first n followees of the user
	 * 
	 * @param user
	 * @param n
	 * @return
	 */
	public List<User> getNFollowees(User user, int n){
		return relationDao.getMinMaxFollowees(user, 0, n);
	}
	
	/**
	 * query users by the query string
	 * 
	 * @param qstr
	 * @return
	 */
	public List<User> queryUser(String qstr){
		return userDao.queryUser(qstr);
	}
	
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	public void setRelationDao(RelationDao relationDao) {
		this.relationDao = relationDao;
	}
	
}
